package com.han.yrpc.core.provider;

import com.han.yrpc.core.registry.ServiceRegistry;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@AllArgsConstructor
public class ProviderBeanPostProcessor implements BeanPostProcessor {

    private final ServiceRegistry serviceRegistry;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean.getClass().isAnnotationPresent(YrpcProvider.class)) {
            Class<?> orElse = Arrays.stream(bean.getClass().getInterfaces()).findFirst().orElse(null);
            String name = orElse != null ? orElse.getName() : "unKnown";
            serviceRegistry.registry(name, bean);
        }
        return bean;
    }
}
